package com.mkyong.common.repository.dao.impl;

import java.util.Collection;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.mkyong.common.model.Question;
import com.mkyong.common.repository.dao.QuestionDao;
import com.mkyong.common.repository.rowmapper.QuestionRowMapper;

public class QuestionDaoImpl implements QuestionDao {

    private SimpleJdbcTemplate simpleJdbcTemplate;

    private SimpleJdbcInsert insertQuestion;

    public QuestionDaoImpl(DataSource dataSource) {
        this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);

        insertQuestion = new SimpleJdbcInsert(dataSource).withTableName("question")
                .usingGeneratedKeyColumns("id");
    }

    @Override
    public void save(Question question) {
        Number newKey = this.insertQuestion.executeAndReturnKey(new BeanPropertySqlParameterSource(
                question));
        question.setId(newKey.intValue());
    }

    @Override
    public Question getQuestionById(long questionId) {
        Question question = null;
        try {
            question = this.simpleJdbcTemplate.queryForObject(
                    "SELECT ID, TITLE, CONTENT FROM QUESTION WHERE ID = ?",
                    new QuestionRowMapper(), questionId);
        } catch (EmptyResultDataAccessException ex) {
            ex.printStackTrace();
        }

        System.out.println("%%%%%%%%%%%%%%%%%" + question.getId() + "%%%%%%%%%%%%%%%%%");
        return question;
    }

    @Override
    public void modifyQuestion(Question question) {
        this.simpleJdbcTemplate.update(
                "UPDATE question SET title=:title, content=:content WHERE id=:id",
                new BeanPropertySqlParameterSource(question));

    }

    @Override
    @Transactional(readOnly = true)
    public Collection<Question> sortQuestions(String sort) {
        List<Question> questions = this.simpleJdbcTemplate.query(
                "SELECT ID, TITLE, CONTENT FROM QUESTION", new QuestionRowMapper());
        return questions;
    }

}
